package com.atguigu.security;

import com.alibaba.dubbo.config.annotation.Reference;
import com.atguigu.pojo.Permission;
import com.atguigu.pojo.Role;
import com.atguigu.pojo.User;
import com.atguigu.service.UserService;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.HashSet;
import java.util.Set;

/**
 * @Author LEO
 * @Date 2021年12月23日 16:14
 */
@Component("springSecurityUserService")
public class SpringSecurityUserService implements UserDetailsService {

    @Reference
    private UserService userService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
       // 查询用户信息，以及用户对应角色，以及角色权限
        User user = userService.findUserByUsername(username);
        if (user==null){ //不存在这个用户
            return null;   //返回null给框架， 框架会抛异常，进行异常处理，跳转到登录页面
        }
        Set<Role> roles = user.getRoles();  // 集合数据由RoleDao查询
        // 2. 创建权限集合
        HashSet<GrantedAuthority> authorities = new HashSet<>();
        for (Role role : roles) {
            //获取许可
            Set<Permission> permissions = role.getPermissions(); //集合数据由PermissionDao查询
            for (Permission permission : permissions) {
                //授权
                authorities.add(new SimpleGrantedAuthority(permission.getKeyword()));
            }
        }
        /**
         * User()     返回类型 UserDetails userDetails
         * 1：指定用户名
         * 2：指定密码（SpringSecurity会自动对密码进行校验）
         * 3：传递授予的角色和权限
         */
        org.springframework.security.core.userdetails.User securityUser =
                new org.springframework.security.core.userdetails.User(user.getUsername(),user.getPassword(),authorities);

        return securityUser;
    }
}
